package cn.net.zhenchan.controller;

import cn.net.zhenchan.base.action.BaseClassAction;
import cn.net.zhenchan.common.MD5Utils;
import cn.net.zhenchan.common.ServiceMessage;
import cn.net.zhenchan.enums.MsgStatus;
import cn.net.zhenchan.model.User;
import cn.net.zhenchan.service.BbsUserService;
import cn.net.zhenchan.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@SuppressWarnings("rawtypes")
@Controller
@RequestMapping("/bbsUser")
public class BbsUserController extends BaseClassAction {
	private Logger logger = LoggerFactory.getLogger(BbsUserController.class);
	@Autowired
	private BbsUserService bbsUserService;
	
	@RequestMapping("/bbs_user_manager")
	public String bbsUserManager(){
		return "manager/bbs_user";
	}
	
	@RequestMapping(value="/bbsUserList",method= RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> bbsUserList(HttpServletRequest request, HttpServletResponse response, User user){
		Map<String,Object> resultMap = null;
		try{
			int pageSize=10,pageNo=1;
			if(null != request.getParameter("page")){
				pageNo = Integer.parseInt(request.getParameter("page"));
			}
			if(null != request.getParameter("rows")){
				pageSize= Integer.parseInt(request.getParameter("rows"));
			}
			resultMap = bbsUserService.queryAllUsersByPage(user, pageNo, pageSize);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return resultMap;
	}
	/**
	 * 获取指定的关键字
	 * @param request
	 * @param response
	 * @param getId
	 */
	@RequestMapping(value="/getBean/{getId}",method= RequestMethod.POST)
	public void getBean(HttpServletRequest request, HttpServletResponse response, @PathVariable Object getId){
		try{
			if(getId!=null && getId.toString().length()>0){
				User user = bbsUserService.queryUserById(Long.valueOf(String.valueOf(getId)));
				super.writeClient(response, super.ObjectChangJSONObject(user).toString(), "");
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
		
	}
	/**
	 * 保存或者更新
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/saveOrUpdate",method= RequestMethod.POST)
	@ResponseBody
	public String saveOrUpdate(HttpServletRequest request, HttpServletResponse response, User user){
		try{
			
			ServiceMessage<String> msg = null;
			if(user.getUserId() != null){//修改
				user.setPassword(MD5Utils.MD5(user.getPassword()));
				msg = bbsUserService.updateUser(user);
				if(!msg.getStatus().equals(MsgStatus.NORMAL)){
					logger.error("服务异常");
	                return "服务异常";
				}else{
					return "ok";
				}
			}else{//保存
				//保存前先判断用户名是否存在
				User existsUser = bbsUserService.queryUserNameExists(user);
				if(existsUser != null){
					return "exists";
				}
				user.setPassword(MD5Utils.MD5(user.getPassword()));
				user.setIsDisabled(0);
				user.setProhibitPost(0);
				user.setRegisterIp(Utils.getRemortIP(request));
				user.setRegisterTime(new Date());
				user.setIsDelete("N");
				msg = bbsUserService.addUser(user);
				if(!msg.getStatus().equals(MsgStatus.NORMAL)){
					logger.error("服务异常");
	                return "服务异常";
				}else{
					return "ok";
				}
			}
		}catch(Exception ex){
			ex.printStackTrace();
			return "服务异常";
		}
	}
	/**
	 * 删除关键字（物理删除）
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/deleteLogicByIds",method= RequestMethod.POST)
	@ResponseBody
	public String deleteLogicByIds(HttpServletRequest request, HttpServletResponse response){
		ServiceMessage<String> msg = null;
		try{
			String ids = request.getParameter("ids");
			logger.info("----------->删除关键字------>ids = " + ids);
			if(ids != null && ids.length() > 0){
				List<Long> mList = new ArrayList<Long>();
				String[] myIds = ids.split(",");
				for(String str : myIds){
					mList.add(Long.valueOf(str));
				}
				//调用update接口
				msg = bbsUserService.deleteUserById(mList);
				if(!msg.getStatus().equals(MsgStatus.NORMAL)){
					logger.error("服务异常");
	                return "服务异常";
				}else{
					return "ok";
				}
			}else{
				return "请选择要删除的关键词";
			}
		}catch(Exception ex){
			ex.printStackTrace();
			return "服务异常";
		}
	}
	@RequestMapping(value="/checkUsedOrNot",method= RequestMethod.POST)
	@ResponseBody
	public String checkUsedOrNot(HttpServletRequest request, HttpServletResponse response){
		try{
			ServiceMessage<String> msg = null;
			
			String userId = request.getParameter("userId");
			String isDisabled = request.getParameter("isDisabled");
			
			User user = new User();
			user.setUserId(Long.valueOf(userId));
			user.setIsDisabled(Integer.valueOf(isDisabled));
			
			msg = bbsUserService.updateUser(user);
			if(!msg.getStatus().equals(MsgStatus.NORMAL)){
				logger.error("服务异常");
                return "服务异常";
			}else{
				return "ok";
			}
		}catch(Exception ex){
			ex.printStackTrace();
			return "服务异常";
		}
	}
}
